﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    TokenController
// 创建者：      杨程
// 创建日期：	    2022/12/29 14:27:10

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.ViewModels.WebApi.Controllers;

/// <summary>
///
/// </summary>
[ApiController]
[Route("[controller]/[action]")]
public partial class AuthController : Controller
{
    /// <summary>
    ///
    /// </summary>
    public AuthController()
    {
        //构造函数
    }

    /// <summary>
    /// 获取Token
    /// </summary>
    /// <param name="UserId">用户名</param>
    /// <param name="Password">密码</param>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public ActionResult<string> GetToken(string UserId, string Password)
    {
        var repUser = VampirewalCoreContext.GetInstance().GetService<SqlSugarRepository<Sys_User>>();

        var user = repUser.SingleAsync(s => s.UserId == UserId && s.Password == Password);

        if (user == null)
        {
        }

        //DateTime utc = DateTime.UtcNow;
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Jti,"1"),//编号
            new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//签发时间
            new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//生效时间
             // 过期时间 100秒
            new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(100)).ToUnixTimeSeconds()}"),
            new Claim(JwtRegisteredClaimNames.Iss,"VampirewalAdminServer"), // 签发者
            new Claim(JwtRegisteredClaimNames.Aud,"VampirewalAdminClient") // 接收者
        };

        // 密钥
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VampirewalAdminServer"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var tokenHandler = new JwtSecurityTokenHandler();

        JwtSecurityToken jwt = new JwtSecurityToken(

            claims: claims,// 声明的集合
                           //expires: .AddSeconds(36), // token的有效时间
            signingCredentials: creds
            );
        var handler = new JwtSecurityTokenHandler();
        // 生成 jwt字符串
        var strJWT = handler.WriteToken(jwt);

        //HttpContext.SigninToSwagger(strJWT);
        return Ok(strJWT);
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <param name="UserId">用户ID</param>
    /// <param name="Password">密码</param>
    /// <returns></returns>
    [Authorize]
    [HttpGet]
    public async Task<Sys_User> GetUserInfo(string UserId, string Password)
    {
        var repUser = VampirewalCoreContext.GetInstance().GetService<SqlSugarRepository<Sys_User>>();

        var user = await repUser.SingleAsync(s => s.UserId == UserId && s.Password == Password);

        if (user != null)
        {
            return user;
        }

        return default(Sys_User);
    }
}

public static class SwaggerEx
{
    public static void SigninToSwagger(this HttpContext httpContext, string accessToken)
    {
        httpContext.Response.Headers["access-token"] = accessToken;
    }

    /// <summary>
    /// 设置规范化文档退出登录
    /// </summary>
    /// <param name="httpContext"></param>
    public static void SignoutToSwagger(this HttpContext httpContext)
    {
        httpContext.Response.Headers["access-token"] = "invalid_token";
    }
}